//
//  ZMyOrderCarShopOrderCell.m
//  DistributorAB
//
//  Created by LZY on 2019/10/11.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "ZMyOrderCarShopOrderCell.h"
@interface ZMyOrderCarShopOrderCell () <UITextFieldDelegate>
@property (nonatomic, strong) UIView *viewBg;//背景
@property (nonatomic, strong) UIButton *btnCycle;//选中按钮
@property (nonatomic, strong) UIImageView *ivShop;//产品图片
@property (nonatomic, strong) UILabel *lblName;//产品名称
@property (nonatomic, strong) UILabel *lblType;//产品型号
@property (nonatomic, strong) UILabel *lblPrice;//产品价格(省级经销商才显示)
@property (nonatomic, strong) UIButton *btnReduce;//-
@property (nonatomic, strong) UIButton *btnAdd;//+
@property (nonatomic, strong) UITextField *tfBuy;//购买个数
@property (nonatomic, assign) BOOL isUpdateNumber;//是否正在更新数据
@end

@implementation ZMyOrderCarShopOrderCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupViewAction];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

#pragma mark - 界面布局
- (void)setupViewAction{
    self.contentView.backgroundColor = kColorWithHex(0xf2f2f2);
    [self.contentView addSubview:self.viewBg];
    [self.viewBg addSubview:self.btnCycle];
    [self.viewBg addSubview:self.ivShop];
    [self.viewBg addSubview:self.lblName];
    [self.viewBg addSubview:self.lblType];
    [self.viewBg addSubview:self.lblPrice];
    [self.viewBg addSubview:self.btnAdd];
    [self.viewBg addSubview:self.btnReduce];
    [self.viewBg addSubview:self.tfBuy];
    
    if (AGENT_LEVEL != 1) {
        //非省级的不显示数量
        self.btnAdd.hidden = YES;
        self.tfBuy.hidden = YES;
        self.btnReduce.hidden = YES;
    }
    
    [self.btnCycle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.viewBg.mas_leading).offset(3);
        make.top.equalTo(self.viewBg.mas_top).offset(17);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    [self.ivShop mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.viewBg.mas_top);
        make.leading.equalTo(self.btnCycle.mas_trailing).offset(2);
        make.size.mas_equalTo(CGSizeMake(64, 64));
    }];
    [self.lblName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.viewBg.mas_top);
        make.leading.equalTo(self.ivShop.mas_trailing).offset(10);
        make.trailing.equalTo(self.viewBg.mas_trailing).offset(-10);
        make.height.mas_equalTo(20);
    }];
    UILabel *lblNotice = [UILabel new];
    lblNotice.text = @"型号";
    lblNotice.font = [UIFont systemFontOfSize:12];
    lblNotice.textColor = kColorWithHex(0x666666);
    [self.viewBg addSubview:lblNotice];
    [lblNotice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.lblName);
        make.top.equalTo(self.lblName.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(30, 16));
    }];
    [self.lblType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lblNotice.mas_centerY);
        make.leading.equalTo(lblNotice.mas_trailing).offset(10);
        make.trailing.equalTo(self.viewBg.mas_trailing).offset(-10);
        make.height.equalTo(lblNotice.mas_height);
    }];
    [self.lblPrice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.lblName.mas_leading);
        make.top.equalTo(lblNotice.mas_bottom).offset(6);
        make.trailing.equalTo(self.viewBg.mas_trailing).offset(-100);
        make.height.mas_equalTo(25);
    }];
    [self.btnAdd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.viewBg.mas_trailing).offset(-10);
        make.bottom.equalTo(self.viewBg.mas_bottom).offset(-15);
        make.size.mas_equalTo(CGSizeMake(25, 19));
    }];
    [self.tfBuy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.btnAdd.mas_leading);
        make.centerY.equalTo(self.btnAdd.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(30, 19));
    }];
    [self.btnReduce mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.tfBuy.mas_leading);
        make.centerY.equalTo(self.btnAdd.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(25, 19));
    }];
}
#pragma mark - 更新数据
- (void)setPartModel:(BShopPartModel *)partModel{
    if (partModel) {
        _partModel = partModel;
        [HFTools imageViewUpdateWithUrl:partModel.image_url withImageView:self.ivShop withPlaceholderImage:@""];
        self.lblName.text = partModel.parts_name;
        self.lblType.text = partModel.name;
        self.tfBuy.text = partModel.count;
        self.btnCycle.selected = partModel.isOrderSelected;
        if (AGENT_LEVEL == 1) {
            self.lblPrice.text = [NSString stringWithFormat:@"￥%@",partModel.salePrice];
        }
    }
    
    //省级经销商
    NSInteger agentType = [[USER_DEFAULT objectForKey:@"level"] integerValue];
    if (agentType == 1) {
        self.lblPrice.hidden = NO;
        
    }
}
- (void)setIsRoundBg:(BOOL)isRoundBg{
    UIBezierPath *maskPath;
    if (isRoundBg) {
        maskPath = [UIBezierPath bezierPathWithRoundedRect:self.viewBg.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(6, 6)];
    }else{
        maskPath = [UIBezierPath bezierPathWithRoundedRect:self.viewBg.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(0, 0)];
    }
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.viewBg.bounds;
    maskLayer.path = maskPath.CGPath;
    self.viewBg.layer.mask = maskLayer;
    [self.contentView addSubview:self.viewBg];
}
#pragma mark - 交互事件
//选中按钮
- (void)btnCycleClickAction:(UIButton *)sender{
    if (self.partModel && self.delegate && [self.delegate respondsToSelector:@selector(orderCarShopOrderCellClick:isSelected:)]) {
        if (self.partModel.isOrderSelected) {
            self.partModel.isOrderSelected = NO;
            [self.delegate orderCarShopOrderCellClick:self.indexPath isSelected:NO];
            sender.selected = NO;
           
        }else{
            self.partModel.isOrderSelected = YES;
            [self.delegate orderCarShopOrderCellClick:self.indexPath isSelected:YES];
            sender.selected = YES;
        }
    }
}
//-按钮
- (void)btnReduceClickAction:(UIButton *)sender{
    NSInteger buyCount = [self.partModel.count integerValue];
    NSInteger lowCount = [self.partModel.quantity integerValue];//最低购买量
    
    if (buyCount > lowCount) {
        buyCount--;
        [self updatePartNumberWith:[NSString stringWithFormat:@"%ld",buyCount]];
    }else{
        NSString *noticeStr = [NSString stringWithFormat:@"该产品至少购买%ld个",lowCount];
        ShowToastWithText(noticeStr);
    }
    
}
//+按钮
- (void)btnAddClickAction:(UIButton *)sender{
    [self updatePartNumberWith:[NSString stringWithFormat:@"%ld",[self.partModel.count integerValue] + 1]];
}
#pragma mark - 购买数量label添加上下边框
- (void)borderForTextField:(UITextField *)tf{
    
    // 线的路径
    UIBezierPath * bezierPath = [UIBezierPath bezierPath];
    
    // top线路径
    [bezierPath moveToPoint:CGPointMake(0.0f, 0.0f)];
    [bezierPath addLineToPoint:CGPointMake(30, 0.0f)];
    // bottom线路径
    [bezierPath moveToPoint:CGPointMake(0.0f, 19)];
    [bezierPath addLineToPoint:CGPointMake(30, 19)];
    
    
    CAShapeLayer * shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = kColorWithHex(0x979797).CGColor;
    shapeLayer.fillColor  = [UIColor clearColor].CGColor;
    // 添加路径
    shapeLayer.path = bezierPath.CGPath;
    // 线宽度
    shapeLayer.lineWidth = 1;
    
    [tf.layer addSublayer:shapeLayer];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < string.length) {
        NSString *str = [string substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [str rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    NSString *numberStr = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSInteger lowNumber = [self.partModel.quantity integerValue];
    if ([numberStr integerValue] > lowNumber) {
        [self updatePartNumberWith:numberStr];
    }
    if ([numberStr integerValue] < lowNumber) {
        self.tfBuy.text = self.partModel.quantity;
        NSString *noticeStr = [NSString stringWithFormat:@"该产品最低购买%ld个",lowNumber];
        ShowToastWithText(noticeStr);
    }
}
#pragma mark - 更新配件数量数据请求
- (void)updatePartNumberWith:(NSString *)numberCount{
    if (_isUpdateNumber) {
        return;
    }
    kWeakSelf;
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    [MBProgressHUD showHUDAddedTo:window animated:YES];
    _isUpdateNumber = YES;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObjectIfNotNil:numberCount forKey:@"count"];
    [dict setObjectIfNotNil:self.partModel.Id forKey:@"id"];
    [NetWorkTool POST:UPDATE_PARTS_ORDER param:dict success:^(id dic) {
        weakSelf.isUpdateNumber = NO;
        [MBProgressHUD hideHUDForView:window animated:YES];
        weakSelf.partModel.count = numberCount;
        weakSelf.tfBuy.text = numberCount;
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        weakSelf.isUpdateNumber = NO;
        [MBProgressHUD hideHUDForView:window animated:YES];
    } fail:^(NSError *error) {
        weakSelf.isUpdateNumber = NO;
        [MBProgressHUD hideHUDForView:window animated:YES];
    } needUser:YES];
}
#pragma mark - 懒加载
- (UIView *)viewBg{
    if (!_viewBg) {
        _viewBg = [[UIView alloc] initWithFrame:CGRectMake(10, 0, kScreen_Width - 20, 87)];
        _viewBg.backgroundColor = kColorWithHex(0xffffff);
    }
    return _viewBg;
}
- (UIButton *)btnCycle{
    if (!_btnCycle) {
        _btnCycle = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnCycle setImage:imgname(@"cycle_normal_gray_icon") forState:UIControlStateNormal];
        [_btnCycle setImage:imgname(@"cycle_selected_green_icon") forState:UIControlStateSelected];
        [_btnCycle addTarget:self action:@selector(btnCycleClickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnCycle;
}
- (UIImageView *)ivShop{
    if (!_ivShop) {
        _ivShop = [UIImageView new];
    }
    return _ivShop;
}
- (UILabel *)lblName{
    if (!_lblName) {
        _lblName = [UILabel new];
        _lblName.font = [UIFont systemFontOfSize:12];
        _lblName.textColor = kColorWithHex(0x5f5f5f);
    }
    return _lblName;
}
- (UILabel *)lblType{
    if (!_lblType) {
        _lblType = [UILabel new];
        _lblType.font = [UIFont boldSystemFontOfSize:12];
        _lblType.textColor = kColorWithHex(0x272727);
    }
    return _lblType;
}
- (UILabel *)lblPrice{
    if (!_lblPrice) {
        _lblPrice = [UILabel new];
        _lblPrice.font = [UIFont systemFontOfSize:18];
        _lblPrice.textColor = kColorWithHex(0x70be68);
        _lblPrice.hidden = YES;
    }
    return _lblPrice;
}
- (UIButton *)btnReduce{
    if (!_btnReduce) {
        _btnReduce = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnReduce setImage:imgname(@"btn_reduce_icon") forState:UIControlStateNormal];
        [_btnReduce addTarget:self action:@selector(btnReduceClickAction:) forControlEvents:UIControlEventTouchUpInside];
        _btnReduce.layer.borderWidth = 1;
        _btnReduce.layer.borderColor = kColorWithHex(0x979797).CGColor;
    }
    return _btnReduce;
}
- (UIButton *)btnAdd{
    if (!_btnAdd) {
        _btnAdd = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnAdd setImage:imgname(@"btn_add_icon") forState:UIControlStateNormal];
        [_btnAdd addTarget:self action:@selector(btnAddClickAction:) forControlEvents:UIControlEventTouchUpInside];
        _btnAdd.layer.borderWidth = 1;
        _btnAdd.layer.borderColor = kColorWithHex(0x979797).CGColor;
    }
    return _btnAdd;
}
- (UITextField *)tfBuy{
    if (!_tfBuy) {
        _tfBuy = [UITextField new];
        _tfBuy.font = [UIFont systemFontOfSize:12];
        _tfBuy.textColor = kColorWithHex(0x666666);
        _tfBuy.textAlignment = NSTextAlignmentCenter;
        _tfBuy.keyboardType = UIKeyboardTypeNumberPad;
        _tfBuy.delegate = self;
        [self borderForTextField:_tfBuy];
    }
    return _tfBuy;
}


+ (CGFloat)cellHeight{
    return 87.0;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
